package control;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.UserData;

/**
 * Servlet implementation class UpdateAccount
 */
public class UpdateAccount extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateAccount() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession();
		UserData us = new UserData();
		String semail = (String) session.getAttribute("email");
		String date = request.getParameter("date");
		String sex = request.getParameter("sex");
		String phone = request.getParameter("phone");
		String phone_err = "";
		String date_err = "";
		if(date.equals("")){
			date_err = "bạn chưa nhập ngày sinh";
		}
		if(phone.equals("")){
			phone_err = "Ban chưa nhập số diện thoại";
		}else {
			Pattern patternObject = Pattern .compile("^[_0-9-\\+]+(\\.[0-9-])*$"); 
			Matcher matcherObject = patternObject.matcher(phone);
			if (!matcherObject.matches()) {
				phone_err += "số dien thoại nhập không hợp lệ";
			}
			String url = "/confirm.jsp";
			if(date_err.equals("")&& phone_err.equals("")){
				try {
					us.updateAccount(semail, date, phone, sex);
				} catch (Exception e) {
					// TODO: handle exception
					response.sendRedirect("updateAccount.jsp");
				}
				
			}
			if(date_err.length()>0||phone_err.length()>0){
				request.setAttribute("phone_err", phone_err);
				request.setAttribute("date_err", date_err);
				url ="updateAccount.jsp";
			}
			RequestDispatcher rd = getServletContext().getRequestDispatcher(url);
			rd.forward(request, response);
	}

}}
